﻿using System;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;

namespace LayuiBlazor.Components
{
    /// <summary>
    /// BootstrapBlazorDataAnnotationsValidator 验证组件
    /// </summary>
    public class LayuiBlazorDataAnnotationsValidator : ComponentBase
    {
        /// <summary>
        /// 获得/设置 当前编辑数据上下文
        /// </summary>
        [CascadingParameter]
        private EditContext? CurrentEditContext { get; set; }

        /// <summary>
        /// 获得/设置 当前编辑窗体上下文
        /// </summary>
        [CascadingParameter]
        public ValidateForm? EditForm { get; set; }

        /// <summary>
        /// 初始化方法
        /// </summary>
        protected override void OnInitialized()
        {
            if (EditForm == null)
            {
                throw new InvalidOperationException($"{nameof(LayuiBlazorDataAnnotationsValidator)} requires a cascading " +
                    $"parameter of type {nameof(ValidateForm)}. For example, you can use {nameof(LayuiBlazorDataAnnotationsValidator)} " +
                    $"inside an {nameof(ValidateForm)}.");
            }

            if (CurrentEditContext == null)
            {
                throw new InvalidOperationException($"{nameof(LayuiBlazorDataAnnotationsValidator)} requires a cascading parameter of type {nameof(EditContext)}. For example, you can use {nameof(LayuiBlazorDataAnnotationsValidator)} inside an EditForm.");
            }

            CurrentEditContext.AddEditContextDataAnnotationsValidation(EditForm);
        }
    }
}
